from django import forms
from django.core.validators import RegexValidator

from . import models


class RegisterForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, ** kwargs)
        # 配合 bootstrap 表单美化设置 widget 属性 class 以及 placeholder避
        # 免在每个 RegisterForm 类属性由 Field 类实例化时重复设置 widget 属
        # 性.
        for field in self.fields.values():
            # 这里我们遍历了 `self.fields.values() 返回的 odict_items 对象
            # `, 而不是遍历 `collections.OrderedDict 对象 self.fields`.
            # self.fields['username'] 和 self.fields['emial'] 这些单键对应
            # 的 field 对象可以通过 self.fields 快速获取，但
            # self.fields.values() 更适合迭代出全部的 form field.
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入{}'.format(field.label)
            field.required = False
        
    phone = forms.CharField(
        label='手机号',
        validators=[RegexValidator(r'^(1[3-9])\d{9}$', '手机号格式错误'),]
    )
    password =  forms.CharField(
        label="密码",
        widget=forms.PasswordInput(
            # attrs={'class':'form-control', 'placeholder': "请输入密码"}
        ))
    confirm_password = forms.CharField(
        label = "重复密码",
        widget=forms.PasswordInput(
            # attrs={'class':'form-control', 'placeholder':"请输入验证码"}
        ))
    code = forms.CharField(
        # widget=forms.TextInput('class':'form-control', 'placeholder':"请输入验证码"),
        label='验证码')

    class Meta:
        model = models.UserInfo
        # fields = "__all__"
        fields = ['username', 'password', 'confirm_password', 'phone', 'email', 'code']
